﻿using System.Collections.Generic;
using System.IO;
using Jayden.Dll.Web.HtmlControls;

namespace Jayden.Dll.Web.Controls.Admin
{
	public class DirectorySelect : Select
	{

		public string ServerPath { get { return GetServerAttribute("path", "/"); } set { SetServerAttribute("path", value); } }
		public string ServerPattern { get { return GetServerAttribute("pattern", "*"); } set { SetServerAttribute("pattern", value); } }
		public bool ServerSearchAll { get { return GetServerAttribute("search-all", "true") == "true"; } set { SetServerAttribute("search-all", value ? null : "false"); } }
		public bool ServerDirectories { get { return GetServerAttribute("directories", "true") == "true"; } set { SetServerAttribute("directories", value ? null : "false"); } }
		public bool ServerFiles { get { return GetServerAttribute("files", "true") == "true"; } set { SetServerAttribute("files", value ? null : "false"); } }

		public bool ServerAutoFill { get { return GetServerAttribute("auto-fill", "true") == "true"; } set { SetServerAttribute("auto-fill", value ? null : "false"); } }

		public void FillFromContext(HttpHandlerContext context)
		{
			string baseVirtualPath = ServerPath;
			string pattern = ServerPattern;
			string rootPath = context.MapPath("/");
			string basePhysicalPath = context.MapPath(baseVirtualPath);
			SearchOption option = ServerSearchAll ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
			List<string> values = new List<string>();
			if (ServerFiles)
				values.AddRange(Directory.GetFiles(basePhysicalPath, pattern, option));
			if (ServerDirectories)
			{
				values.Add(rootPath);
				values.AddRange(Directory.GetDirectories(basePhysicalPath, pattern, option));
			}

			values.Sort();

			Clear();
			AddDefaultOption();
			foreach (string value in values)
			{
				string virtualDirectory = "/" + value.Substring(rootPath.Length).Replace("\\", "/");
				AddOption(null, virtualDirectory);
			}

		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			if (ServerAutoFill)
				FillFromContext(context);
			base.ProcessHtmlRequest(context);
		}
	}
}
